﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ScriptCompare
{
    public static class LineUtility
    {
        public static ScriptLineSortComparer LineSortComparer
        {
            get { return new ScriptLineSortComparer(); }
        }

        public class ScriptLineSortComparer : IComparer<ScriptLine>
        {
            #region IComparer<ScriptLine> Members

            public int Compare(ScriptLine x, ScriptLine y)
            {
                if (x.LineNumber > y.LineNumber)
                    return (-1);
                else if (x.LineNumber < y.LineNumber)
                    return (1);
                else
                    return (0);
            }

            #endregion
        }

        public static string[] TokenizeLine(string lineText)
        {
            return TokenizeLine(lineText, null);
        }

        public static string[] TokenizeLine(string lineText, params char[] additionalDelimiters)
        {
            List<char> delimiters = new List<char>();

            if (additionalDelimiters != null) { delimiters.AddRange(additionalDelimiters); }
            if (!delimiters.Contains(' ')) { delimiters.Add(' '); }
            
            string[] sigTokens = lineText.Split(delimiters.ToArray());

            List<string> goodTokens = new List<string>();

            string token = "";
            for (int i = 0; i < sigTokens.Length; i++)
            {
                token = sigTokens[i].ToLower().Trim();

                if (!String.IsNullOrEmpty(token) && token != " ")
                    goodTokens.Add(token);
            }

            return (goodTokens).ToArray();
        }

        public static string FindTokenAfterString(string[] tokens, string[] searchStrings)
        {
            if (tokens == null)
                throw new ArgumentNullException("tokens");

            int lastPossiblePosition = tokens.Length - 2;

            for (int i = 0; i < tokens.Length; i++)
            {
                foreach (string searchValue in searchStrings)
                {
                    if (
                        (tokens[i] == searchValue.Trim().ToLower()) &&
                        (i < lastPossiblePosition)
                       )
                    {
                        return (tokens[i + 1]);
                    }
                }
            }

            return (String.Empty);
        }
    }
}
